package com.atan.weblog.admin.service.impl;

import com.atan.weblog.admin.model.vo.tag.*;
import com.atan.weblog.admin.service.AdminTagService;
import com.atan.weblog.common.domain.dos.ArticleTagRelDO;
import com.atan.weblog.common.domain.dos.TagDO;
import com.atan.weblog.common.domain.mapper.ArticleTagRelMapper;
import com.atan.weblog.common.domain.mapper.TagMapper;
import com.atan.weblog.common.enums.ResCodeEnum;
import com.atan.weblog.common.exception.BizException;
import com.atan.weblog.common.model.vo.SelectRspVO;
import com.atan.weblog.common.utils.PageResponseUtil;
import com.atan.weblog.common.utils.ResponseUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminTagServiceImpl extends ServiceImpl<TagMapper, TagDO> implements AdminTagService {
    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleTagRelMapper articleTagRelMapper;
    /**
     * 添加标签集合
     * @param addTagReqVO
     * @return
     */
    @Override
    public ResponseUtil addTags(AddTagReqVO addTagReqVO) {
        // vo -> do
        List<TagDO> tagDOS = addTagReqVO.getTagName()
                .stream()
                .distinct() //去掉重复的标签
                .map(name->TagDO.builder()
                        .name(name.trim()) //去掉空格
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build())
                .toList();
        //批量插入
        try {
            saveBatch(tagDOS);
        } catch (Exception e) {
           log.warn("该标签已存在",e);
        }
        return ResponseUtil.success();
    }

    /**
     * 分页标签查询
     * @param findCategoryPageListReqVO
     * @return
     */

    @Override
    public PageResponseUtil findTagPageList(FindTagPageListReqVO findCategoryPageListReqVO) {
        //获取分页参数 查询条件
        long curent = findCategoryPageListReqVO.getCurrent();
        long size = findCategoryPageListReqVO.getSize();
        LocalDate startDate = findCategoryPageListReqVO.getStartDate();
        LocalDate endDate = findCategoryPageListReqVO.getEndDate();
        String name  = findCategoryPageListReqVO.getName();
        Page<TagDO> tagDOPage = tagMapper.selectTagPageList(curent, size, name, startDate, endDate);
        List<TagDO> records = tagDOPage.getRecords();
        //do -> vo
        List<FindTagPageListRepVO> vos = null;
        if(!CollectionUtils.isEmpty(records)) {
            vos = records.stream().map(tagDO -> FindTagPageListRepVO.builder()
                            .id(tagDO.getId())
                            .name(tagDO.getName())
                            .createTime(tagDO.getCreateTime())
                            .build())
                    .collect(Collectors.toList());
        }
        return PageResponseUtil.success(tagDOPage, vos);
    }

    /**
     * 删除标签
     * @param deleteTagReqVO
     * @return
     */
    @Override
    public ResponseUtil deleteTag(DeleteTagReqVO deleteTagReqVO) {
        ArticleTagRelDO articleTagRelDO = articleTagRelMapper.selectOneByTagId(deleteTagReqVO.getId());
        if(Objects.nonNull(articleTagRelDO)){
            log.warn("==> 此标签下包含文章，无法删除，tagId: {}", deleteTagReqVO.getId());
            throw new BizException(ResCodeEnum.TAG_CAN_NOT_DELETE);
        }

        int count = tagMapper.deleteById(deleteTagReqVO.getId());
        return count > 0 ? ResponseUtil.success() : ResponseUtil.fail(ResCodeEnum.TAG_NOT_EXIST);
    }

    /**
     * 根据标签关键字模糊查询
     * @param searchTagReqVO
     * @return
     */
    @Override
    public ResponseUtil searchTag(SearchTagReqVO searchTagReqVO) {
        List<TagDO> tagDOS = tagMapper.searchTag(searchTagReqVO.getKey());
        //do -> vo
        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOS)){
            vos = tagDOS.stream().map(tagDO -> SelectRspVO.builder()
                            .value(tagDO.getId())
                            .label(tagDO.getName())
                            .build())
                    .collect(Collectors.toList());
        }
        return ResponseUtil.success(vos);
    }

    @Override
    public ResponseUtil findTagSelectList() {
        // 查询所有标签, Wrappers.emptyWrapper() 表示查询条件为空
        List<TagDO> tagDOS = tagMapper.selectList(Wrappers.emptyWrapper());

        // DO 转 VO
        List<SelectRspVO> vos = null;
        if (!CollectionUtils.isEmpty(tagDOS)) {
            vos = tagDOS.stream()
                    .map(tagDO -> SelectRspVO.builder()
                            .label(tagDO.getName())
                            .value(tagDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }

        return ResponseUtil.success(vos);
    }
}
